package org.jawa.web;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.jawa.Constants;
import org.jawa.model.User;
import org.jawa.service.UserExistsException;
import org.jawa.service.UserManager;
import org.springframework.security.AccessDeniedException;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class SignupAction extends ActionSupport {

	private static final long serialVersionUID = 3202007752457507709L;
	private final Log log=LogFactory.getLog(SignupAction.class);
	private User user;
	private String cancel;
	private UserManager userManager;
	private static final String CANCEL = "cancel";
	public User getUser() {
		return user;
	}
	
	public void setUser(User user) {
		this.user = user;
	}
	
	public void setCancel(String cancel) {
		this.cancel = cancel;
	}
	
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
	public String execute(){
		if(cancel!=null){
			return CANCEL;
		}
		if(ServletActionContext.getRequest().getMethod().equals("GET")){
			return INPUT;
		}
		return SUCCESS;
	}
	
	public String doDefault(){
		return INPUT;
	}
	
	@SuppressWarnings("unchecked")
	public String save(){
		user.setEnabled(true);
		try{
			userManager.saveUser(user);
			
			List args = new ArrayList();
	        args.add(user.getUsername());
			ActionContext.getContext().getSession().put("message", 
	                getText("user.saved", args));
			ActionContext.getContext().getSession().put(Constants.REGISTERED, Boolean.TRUE);
			UsernamePasswordAuthenticationToken auth=new UsernamePasswordAuthenticationToken(user.getUsername(),user.getConfirmPassword(),user.getAuthorities());
			auth.setDetails(user);
			SecurityContextHolder.getContext().setAuthentication(auth);
			return SUCCESS;
		}catch(AccessDeniedException ade) {
			ActionContext.getContext().getSession().put("message", "AccessDenied failed");
            return INPUT;
		}catch (UserExistsException e) {
			log.warn(e.getMessage());
            List<String> args = new ArrayList<String>();
            args.add(user.getUsername());
            args.add(user.getEmail());
            addActionError(getText("errors.existing.user", args));

            // redisplay the unencrypted passwords
            user.setPassword(user.getConfirmPassword());
            return INPUT;
		}
	}	
}
